import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import '../css/tab.css';

// 利用react-redux实现的简单tab切换和删除，内部代码需要根据lists.js的数据结构自定义写

// action
const switchAtion = (index) => ({
  type: 'SWITCH',
  payload: index
})
const removeAtion = (flag) => ({
  type: 'REMOVE',
  payload: flag
})
// reducer
const switchReducer = (state = {active: 0, flag:null}, action) => {
  switch (action.type) {
    case 'SWITCH':
      return {active: action.payload, flag: null}
    case 'REMOVE':
      return {...state, flag: action.payload}
    default :
      return state
  }
}
// store
const store = createStore(switchReducer);
// 新闻列表
class TabList extends React.Component {
  render() {
    let {src, author, title, job, newContent, readNum, flag, removeSelf} = this.props;
    return (<div className="new-list clearfix">
      <img src={src} />
      <div className="new-body">
        <h3>{title}</h3>
        <p className="new-author"><span>{author}</span>({job})</p>
        <p className="new-content">{newContent}<a href="javascript:;">...[查看全部]</a></p>
        <p className="new-read">此处问题有{readNum}人回答</p>
        <a onClick={() => removeSelf(flag)} className="new-remove" href="javascript:;">删除</a>
      </div>
    </div>)
    
  }
}
// 导航条加新闻列表
class Tab extends React.Component {
  render() {
    let {lists, tabSwitch, removeSelf, active, flag, data} = this.props;
    if(flag !== null) {
      data[`newList${active}`][flag].show = false;
    }
    
    return (<div>
      <ul className="nav">
      {
        lists.map((val,i)=><li onClick={() => tabSwitch(i)} className={i == active ? 'active' : ''} key={i}>{val}</li>) 
      }
      </ul>
      {
        data[`newList${active}`].map((val,i)=>{
          if(val.show)
            return <TabList key={i} {...val} flag={i} removeSelf={removeSelf} />
        })
      }
    </div>)
  }
}
// 链接器connect
let mapStateToProps = (state) => ({active: state.active, flag: state.flag});
let mapDispatchToProps = (dispatch) => ({
  tabSwitch: (i) => dispatch(switchAtion(i)),
  removeSelf: (flag) => dispatch(removeAtion(flag))
});
let NewTab = connect(mapStateToProps, mapDispatchToProps)(Tab);

ReactDOM.render(
  <Provider store={store}>
    <NewTab lists={lists} data={data} />
  </Provider>,
  document.getElementById('root')
)

